# coding: utf-8
from django.http import HttpResponse, JsonResponse
from .utils import IpList
from .utils import SingleDict


def control_serial_number(request):
    """
    控制流水号
    :param request:
    :return: 0 不能操作， 1可以操作
    """
    serial_number = request.GET.get("serialNumber")
    serial_number = str(serial_number)
    lock_type = request.GET.get("type")
    print(lock_type)
    sd = SingleDict()
    if lock_type == "lock":
        status = sd.get_or_append(serial_number)
        if status:
            print('流水号:%s, 不可操作!' % serial_number)
            return HttpResponse("0")
        else:
            print('流水号:%s, 可操作!' % serial_number)
            return HttpResponse("1")
    else:
        sd.del_flag(serial_number)
        print('流水号:%s, 已解锁!' % serial_number)
        return HttpResponse("1")


def get_ip(request):
    ip = request.GET.get('ip')
    IpList.add_ip(ip)
    return HttpResponse("1")


from fabric.api import run, env

ip_list = IpList.ip_list
# ip_list = ["10.80.48.58"]
env.use_ssh_config = True
env.skip_bad_hosts = True


def restart(request):
    bad_hosts_list = []
    success_host_list = []
    for i in ip_list:
        try:
            env.host_string = i
            print (i)
            print (run('killall gunicorn'))
            success_host_list.append(i)
        except Exception as e:
            print (e)
            bad_hosts_list.append(i)
    if bad_hosts_list:
        context = {"bad_hosts_list": bad_hosts_list,
                   "success_host_list": success_host_list}
    else:
        context = {"success_host_list": success_host_list, "success": "ok"}
    return JsonResponse(context)
